package com.happypets.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 文件上传操作的工具类
 * @author ccitking
 */
public class UploadUtil {
	
	public static   Map<String,String>  fileUpload(HttpServletRequest request){
		
		Map<String,String> resMap=new HashMap<String,String>();
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//判断表单的enctype="multipart/form-data":通过文件流的形式提交表单数据
		boolean isMultipart=ServletFileUpload.isMultipartContent(request);
		if(isMultipart){
		
		/***上传文件之前的准备工作***/
		//确定存放文件目录
		String path= request.getSession().getServletContext().getRealPath("/images");
		System.out.println("path:"+path);
		if(!new File(path).isDirectory()){
			//如果目录不存在，新建目录
			new File(path).mkdirs();
		}
		
		//指定临时文件的目录
		String temp= request.getSession().getServletContext().getRealPath("/temp");
		if(!new File(temp).isDirectory()){
			//如果目录不存在，新建目录
			new File(temp).mkdirs();
		}
		
		/***创建磁盘条目工厂类***/
		DiskFileItemFactory   factory = new DiskFileItemFactory();
		factory.setSizeThreshold(10*1024*1024); //5M
		factory.setRepository(new File(temp));
		
		/***创建ServletFileUpload类实例，来解析request***/
		ServletFileUpload  upload=new ServletFileUpload(factory);
		upload.setSizeMax(10*1024*1024);
		upload.setFileSizeMax(5*1024*1024);
		
		try {
			//解析request请求对象
			List<FileItem>   fileItems= upload.parseRequest(request);
			
			for(FileItem  item:fileItems ){
				//获取表单控件的name属性的值
				String  fieldName=item.getFieldName(); 
				
				//表单控件是普通的文本域，非文件域，type= text  passowrd  radio.....
				if(item.isFormField()){
				//获取普通的文本域的值，并且解决表单乱码 的问题	
				 String value=null;
				try {
					value = item.getString("UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				System.out.println("fileName"+fieldName);
				//将普通文本域的key,value存入map
				resMap.put(fieldName, value);
					
				}else{//type="file",表单控件为文件域控件
				 //获取选择要上传文档的文件名
				 String  selected_fileName=	item.getName();
				 String newFileName=null;
				   if(selected_fileName!=null && !"".equals(selected_fileName)){
					   //截取文件后缀
						 String prfix=selected_fileName.substring(selected_fileName.lastIndexOf("."));
						 //生成新的文体名
						Date date= new  Date();
						SimpleDateFormat  format=new SimpleDateFormat("yyyyMMddHHmmss");
						//新的文件名
						newFileName=format.format(date)+(int)Math.random()*1000+prfix;
				   }
				
				try {
					//通过commons io控件实现的文件上传写出文件流 
					//item.write(new File(path,newFileName));
					
					
					//我们自己手动写上传文件代码实现文件上传
					InputStream  finput=item.getInputStream();
					
					System.out.println(path+"---"+newFileName);
					
					FileOutputStream fout=new FileOutputStream(new File(path,newFileName));
					int len=0;
					byte buffer[]=new byte[1024];
					while( (len=finput.read(buffer))!=-1){
						fout.write(buffer, 0, len);
					}
					fout.close();
					finput.close();
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				//将普通文本域的key,value存入map
				resMap.put(fieldName, newFileName);
				}
			}
			
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resMap;
		
		}else{
			System.out.println("表单的enctype属性的值不是multipart/form-data，请修改!");
		}
		return resMap;
	} 
		
}
